package com.longnuoqi.mydoctor.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.longnuoqi.mydoctor.adapter.NewsViewPagerAdapter;
import com.longnuoqi.mydoctor.entity.News;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Lenovo on 2015/12/25.
 */
public class NewsFragment extends Fragment {
    private HorizontalScrollView scrollView;
    private RadioGroup radioGroup;
    private ViewPager viewPager;
    private NewsViewPagerAdapter adapter;
    private static final String name = "news_channel.txt";
    private List<News> newsList;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.news_layout, container, false);
        initView(view);
        getData();
        return view;
    }

    private void initView(View view) {
        scrollView = (HorizontalScrollView) view.findViewById(R.id.news_scrollview);
        viewPager = (ViewPager) view.findViewById(R.id.news_viewpager);
        radioGroup = (RadioGroup) view.findViewById(R.id.news_radiogroup);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Log.e("================", "radiogroup checked:" + checkedId);
                viewPager.setCurrentItem(checkedId);
            }
        });
    }

    private void getData() { //将频道组件加入到RadioGroup中
        if (!FileUtil.fileIsExist(name)) {
            Log.e("==============", "file:"+name+":is not exist");
            RequestQueue queue = Volley.newRequestQueue(getActivity());
            String url = "http://www.tngou.net/api/info/classify";
            StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    FileUtil.saveFile(s, name);
                    newsList = FileUtil.json4NewsChannel(s);
                    initTab();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                }
            });
            queue.add(request);
        } else {
            Log.e("==============", "file:"+name+":exist");
            String s = FileUtil.readFile(name);
            newsList = FileUtil.json4NewsChannel(s);
            initTab();
        }
    }


    private void initTab() {
        for (int i = 0; i < newsList.size(); i++) {
            RadioButton radioButton = (RadioButton) getLayoutInflater(null).inflate(R.layout.news_channel_tab, null);
            radioButton.setId(i);
            radioButton.setText(newsList.get(i).getTitle());
            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            radioGroup.addView(radioButton, params);
        }
        radioGroup.check(0);//标示，RadioGroup中的第一个选项是默认选项
        initViewPager();
    }


    private void initViewPager() {
        List<Fragment> list = new ArrayList<>();
        for (int i = 0; i < newsList.size(); i++) {
            NewsTypeFragment newsTypeFragment = new NewsTypeFragment();
            Bundle bundle = new Bundle();
            bundle.putInt("id", newsList.get(i).getId());
            newsTypeFragment.setArguments(bundle);
            list.add(newsTypeFragment);
        }
        adapter = new NewsViewPagerAdapter(getChildFragmentManager(), list);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(onPageChangeListener);
        viewPager.setOffscreenPageLimit(1);
        viewPager.setCurrentItem(0);
    }

    private void setTab(int position) {
        RadioButton radioButton = (RadioButton) radioGroup.getChildAt(position);//获取到指定位置的RadioButton
        radioButton.setChecked(true);
        int left = radioButton.getLeft();
        int width = radioButton.getMeasuredWidth();//获得组件的宽度
        DisplayMetrics metrics = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int screenWidth = metrics.widthPixels;//获得屏幕像素数
        int len = left + width / 2 - screenWidth / 2;//获得屏幕中导航频道的数量
        scrollView.smoothScrollTo(len, 0);//进行scrollview横向移动
    }

    private ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            setTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    };
}
